<template>
    <div>
        <!-- 搜索bar -->
        <div id="selectBar">
            <el-select v-model="selectBarData.searchType" placeholder="请选择类别">
                <el-option v-for="(item, index) in timerTypes" :key="index" :value="item" :label="item"></el-option>
            </el-select>
            <el-date-picker v-model="selectBarData.time" type="date" placeholder="请选择时间"></el-date-picker>
            <el-button icon="el-icon-search" class="search" circle @click="search(true)"></el-button>
        </div>
        <!-- 卡片列表 -->
        <ul id="timerBar">
            <li class="timer" v-for="item in timers" :key="item.id" @click="editShow = true; currentTimer = item">
                <!-- 封面图片卡片 -->
                <div class="imgExitTimer"
                    :style="'background-image: url(' + GLOBAL.OSSImageUrlRoot + 'TimerImage/' + item.id + '.png);'"
                    v-if="item.imgModeShow">
                    <!-- 隐藏元素，用来判断封面是否存在 -->
                    <img style="display: none;" :src="GLOBAL.OSSImageUrlRoot + 'TimerImage/' + item.id + '.png'" alt=""
                        @error="notImage(item)">
                    <div class="timerText timerBarTransparent">
                        <div class="textBox" v-if="item.finishTime != null">{{ item.name + ' 共' }}</div>
                        <div class="textBox" v-else>{{ pathOrNot(item.time) ? item.name + ' 已经' : item.name + ' 还有' }}</div>
                    </div>
                    <div class="timerDays timerBarTransparent">
                        <div class="textBox dayTextBox imageExitTextColor dayTransparentColor">
                            {{ getDiffDay(item.time, item.finishTime) }}
                        </div>
                    </div>
                    <div class="timerBottom timerBarTransparent">
                        <div class="textBox imageExitTextColor" style="margin-bottom: 5px;">起始日：{{ item.time }}
                        </div>
                        <div class="textBox imageExitTextColor" v-if="item.finishTime != null"> 结束日：{{ item.finishTime }}
                        </div>
                        <div class="textBox imageExitTextColor" v-else>{{ weekDay[new Date(item.time).getDay()] }}</div>
                    </div>
                </div>
                <!-- 默认卡片 -->
                <div style="height: 100%;" v-else>
                    <div class="timerText" :style="'background-color: ' + item.color">
                        <div class="textBox" v-if="item.finishTime != null">{{ item.name + ' 共' }}</div>
                        <div class="textBox" v-else>{{ pathOrNot(item.time) ? item.name + ' 已经' : item.name + ' 还有' }}</div>
                    </div>
                    <div class="timerDays">
                        <div class="textBox dayTextBox">
                            {{ getDiffDay(item.time, item.finishTime) }}
                        </div>
                    </div>
                    <div class="timerBottom">
                        <div class="textBox" style="margin-bottom: 5px;">起始日：{{ item.time }}</div>
                        <div class="textBox" v-if="item.finishTime != null"> 结束日：{{ item.finishTime }}</div>
                        <div class="textBox" v-else>{{ weekDay[new Date(item.time).getDay()] }}</div>
                    </div>
                </div>
            </li>
        </ul>
        <!-- 分页按钮 -->
        <div id="paging">
            <el-pagination layout="prev, pager, next" :page-size="pageSize" :total="total"
                @current-change="pageCurrentChange">
            </el-pagination>
        </div>
        <!-- 编辑卡片提示框 -->
        <el-dialog title="编辑卡片" :visible.sync="editShow">
            <el-form label-position="top" :model="currentTimer">
                <el-form-item>
                    <span>id：{{ currentTimer.id }}</span>
                </el-form-item>
                <el-form-item label="上传 / 修改卡片图片">
                    <el-image :src="GLOBAL.OSSImageUrlRoot + 'TimerImage/' + currentTimer.id + '.png'" fit="contain"
                        style="height: 80px;"
                        :preview-src-list="[GLOBAL.OSSImageUrlRoot + 'TimerImage/' + currentTimer.id + '.png']">
                        <div slot="error" class="image-slot">
                            <i class="el-icon-picture-outline"></i>
                        </div>
                    </el-image>
                    <el-upload class="upload-demo" :action="uploadUrl" :before-upload="beforeImgUpload" auto-upload
                        :headers="imgUploadHeaders" :on-error="imgUploadError" :on-success="imgUploadSuccess" :limit="1"
                        :on-exceed="handleExceed" accept=".jpg, .png" list-type="picture" :multiple="false"
                        :file-list="fileList" name="file">
                        <el-button size="small" type="primary">点击上传</el-button>
                        <el-button size="small" type="danger" @click.stop="deleteTimerImage">删除图片</el-button>
                        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，无需点击提交自动上传</div>
                    </el-upload>
                </el-form-item>
                <el-form-item label="卡片事件名称">
                    <el-input id="el_input" v-model="currentTimer.name" clearable></el-input>
                </el-form-item>
                <el-form-item label="起始时间">
                    <el-date-picker id="el_input" type="date" placeholder="选择时间卡片日期" value-format="yyyy-MM-dd"
                        v-model="currentTimer.time"></el-date-picker>
                </el-form-item>
                <el-form-item label="结束时间">
                    <el-date-picker id="el_input" type="date" placeholder="选择卡片结束日期" value-format="yyyy-MM-dd"
                        v-model="currentTimer.finishTime"></el-date-picker>
                </el-form-item>
                <el-form-item>
                    卡片事件类别
                    <div class="typeBar">
                        <p>1.选择已有的卡片类型</p>
                        <el-select v-model="currentTimer.type">
                            <el-option v-for="(item, index) in timerTypes" :key="index" :value="item"
                                :label="item"></el-option>
                        </el-select>
                        <p>2.创建新的卡片类型</p>
                        <el-input id="el_input" v-model="currentTimer.type" clearable></el-input>
                    </div>

                </el-form-item>
                <el-form-item label="卡片颜色">
                    <el-color-picker v-model="currentTimer.color" show-alpha :predefine="predefineColors"></el-color-picker>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="editShow = false">取 消</el-button>
                <el-button type="danger" @click="deleteTimer(); editShow = false">删除</el-button>
                <el-button type="primary" @click="timerEdit(); editShow = false">提 交</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        return {
            selectBarData: {
                searchType: null,
                time: null,
            },
            timerTypes: [], // 所有卡片类别的数据
            timers: [], // 卡片展示数据
            searchOrNot: false, // 是否搜索状态量，用于确定翻页后数据从那个方法得到
            currentPage: 1, // 当前页
            pageSize: 12, // 页大小
            total: 0, // 数据总数
            editShow: false, // 控制编辑卡片的显示/隐藏
            currentTimer: {}, // 当前编辑卡片数据
            now: new Date(), // 当天
            predefineColors: [
                '#ee820e', '#ea6878', '#299fea', '#ef5a3b', '#2d2d2d'
            ], // 颜色选择器的预定义颜色
            weekDay: ['星期天', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六',], // 星期数组
            imgUploadHeaders: { 'Token': sessionStorage.getItem('token') }, // 请求头token信息，用于图片上传后端认证
            fileList: [], // 文件(图片)上传的文件list
        }
    },
    computed: {
        uploadUrl() { // 请求上传图片的url地址
            return this.$axios.defaults.baseURL + '/timer/login/uploadImage/' + this.currentTimer.id
        },
    },
    methods: {
        // 当element ui 的页数改变，同步页数
        pageCurrentChange(val) {
            this.currentPage = val // 更改当前页
            if (this.searchOrNot) { // 若搜索过，就用筛选搜索的方式查询数据
                this.search(false)
                return
            }
            this.getTimerData() // 默认，请求所有数据
        },
        // 筛选搜索事件
        search(buttonSearchOrNot) {
            if (buttonSearchOrNot) { // 若为按钮点击搜索,重设页状态
                this.currentPage = 1
                this.total = 0
            }
            this.searchOrNot = true // 改变搜索状态量
            let data = new FormData()
            if (this.selectBarData.searchType != null) data.append("type", this.selectBarData.searchType)
            if (this.selectBarData.time != null) data.append("time", this.selectBarData.time)
            this.$axios({
                method: 'post',
                url: '/timer/login/searchTimer/' + this.currentPage + '/' + this.pageSize,
                data: data,
                headers: {
                    'Content-Type': 'application/x-www-form-urlcoded'
                }
            }).then(res => {
                res.data.data.data.forEach(element => {
                    element.imgModeShow = true
                    element.time = element.time.slice(0, 10)
                    if (element.finishTime != null) element.finishTime = element.finishTime.slice(0, 10)
                });
                this.total = res.data.data.total
                this.timers = res.data.data.data
            })
        },
        // 提交修改时间卡片事件
        timerEdit() {
            let data = new FormData()
            data.append("id", this.currentTimer.id)
            data.append("type", this.currentTimer.type)
            data.append("time", new Date(this.currentTimer.time))
            data.append("name", this.currentTimer.name)
            data.append("color", this.currentTimer.color)
            if (this.currentTimer.finishTime != null) data.append("finishTime", new Date(this.currentTimer.finishTime))
            this.$axios({
                method: 'post',
                url: '/timer/login/updateTimer',
                headers: {
                    'Content-Type': 'application/x-www-form-urlcoded'
                },
                data: data
            }).then(res => {
                if (res.data) {
                    this.$router.go(0)
                    this.$message({
                        showClose: true,
                        message: '提交成功',
                        type: 'success'
                    })
                } else {
                    this.$message({
                        showClose: true,
                        message: '提交失败，出现错误了X.X',
                        type: 'error'
                    })
                }
            })
        },
        // 删除时间卡片
        deleteTimer() {
            this.$confirm('确定删除该时间卡片吗', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'info',
            }).then(() => {
                this.$axios({
                    method: 'post',
                    url: '/timer/login/deleteTimer/' + this.currentTimer.id
                }).then(res => {
                    if (res.data) {
                        this.$router.go(0)
                        this.$message({
                            showClose: true,
                            message: '删除成功',
                            type: 'success'
                        })
                    } else {
                        this.$message({
                            showClose: true,
                            message: '删除失败，出现错误了X.X',
                            type: 'error'
                        })
                    }
                })
            })
        },
        // 获取时间卡片数据
        getTimerData() {
            this.$axios({
                method: 'post',
                url: '/timer/login/getTimer/' + this.currentPage + '/' + this.pageSize,
            }).then(res => {
                res.data.data.data.forEach(element => {
                    element.imgModeShow = true
                    element.time = element.time.slice(0, 10)
                    if (element.finishTime != null) element.finishTime = element.finishTime.slice(0, 10)
                });
                this.total = res.data.data.total
                this.timers = res.data.data.data
            })
        },
        // 获取时间卡片类别数据
        getAllTimerType() {
            this.$axios({
                method: 'post',
                url: '/timer/login/getAllType'
            }).then(res => {
                this.timerTypes = res.data
            })
        },
        // 计算该时间距离现在的天数 还有多少天 或者 已经多少天
        getDiffDay(date_1, date_2) {
            let totalDays, diffDate
            let myDate_1 = Date.parse(date_1)
            let myDate_2
            if (date_2 == null) {
                myDate_2 = Date.parse(this.now)
            } else {
                myDate_2 = Date.parse(date_2)
            }
            diffDate = Math.abs(myDate_1 - myDate_2)
            totalDays = Math.floor(diffDate / (1000 * 3600 * 24))
            if (myDate_1 > myDate_2) { // 若是未来
                return totalDays + 1
            } else {
                return totalDays
            }
        },
        // 判断是否过去
        pathOrNot(time) {
            let date_1 = Date.parse(time)
            let date_now = Date.parse(this.now)
            if (date_1 > date_now) {
                return false
            }
            return true
        },
        // 图片文件上传前的文件类型检查
        beforeImgUpload(file) {
            if (this.getfileName(file.name) != '.jpg' && this.getfileName(file.name) != '.png') {
                this.$message({
                    message: '上传封面图片文件格式只能为jpg或png',
                    type: 'error',
                    showClose: true,
                })
                return false
            }
        },
        // 图片文件上传出现错误的提示事件
        imgUploadError() {
            this.$message({
                message: '文件上传出现错误X.X',
                type: 'error',
                showClose: true,
            })
        },
        // 图片文件上传成功的提示事件
        imgUploadSuccess() {
            this.$message({
                message: '上传成功',
                type: 'success',
                showClose: true
            })
        },
        // 处理图片上传多了的提示事件
        handleExceed() {
            this.$message({
                type: 'error',
                message: '限制只能上传一个文件哦',
                showClose: true,
            })
        },
        // 获取文件后缀工具函数
        getfileName(filename) {
            // 转换为小写
            const pos = filename.toLowerCase().lastIndexOf('.')
            let suffix = ''
            if (pos !== -1) {
                suffix = filename.substring(pos)
            }
            return suffix
        },
        // 没有图片的回调函数
        notImage(item) {
            item.imgModeShow = false
        },
        // 删除卡片图片
        deleteTimerImage() {
            this.$axios({
                method: 'post',
                url: '/timer/login/deleteTimerImage/' + this.currentTimer.id
            }).then(res => {
                if (res.data) {
                    this.$message({
                        showClose: true,
                        message: '删除成功',
                        type: 'success'
                    })
                } else {
                    this.$message({
                        showClose: true,
                        message: '删除失败，出现错误了X.X',
                        type: 'error'
                    })
                }
            })
        }
    },
    mounted() {
        this.getTimerData()
        this.getAllTimerType()
    }
}
</script>

<style lang="scss" scoped>
#selectBar {
    margin: 20px auto;
    display: flex;
    justify-content: center;
}

#timerBar {
    display: flex;
    flex-flow: wrap;
}

.timer {
    width: 20%;
    height: 100%;
    border-radius: 20px;
    margin: 20px 2.5%;
    background-color: #fff;
    box-shadow: rgba(0, 0, 0, 0.3) 0px 5px 8px;
    text-align: center;
    cursor: pointer;
}

.timerText {
    height: 25%;
    display: flex;
    border-radius: 20px 20px 0 0;
    align-items: center;
    padding: 20px 20px;
    font-size: $font-size-small;
    font-weight: $font-weight-medium;
    background-color: #f68802;
    color: #fff;
    overflow: hidden;
}

.timerDays {
    height: 60%;
    font-size: $font-size-large;
    font-weight: $font-weight-large;
    color: #444444;
    display: flex;
    align-items: center;
}

.timerBottom {
    display: flex;
    justify-content: center;
    flex-direction: column;
    width: 100%;
    padding: 5px 0;
    background-color: #f7f5f4;
    border-radius: 0 0 20px 20px;
    font-size: $font-size-x-small;
}

.textBox {
    text-align: center;
    width: 100%;
}

.dayTextBox {
    padding: 5vmin 0;
}

.imgExitTimer {
    height: 100%;
    position: relative;
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
    border-radius: 20px;
}

.timerBarTransparent {
    background-color: rgba(0, 0, 0, 0);
}

.imageExitTextColor {
    color: #fff;
}

.dayTransparentColor {
    color: #e6e3db;
}

.typeBar {
    padding-left: 10px;
}
</style>
<style scoped="scoped">
/* 筛选框 */
/deep/#selectBar .el-input__inner {
    background-color: #202020;
    color: #fff;
}

#selectBar .el-date-editor .el-input,
#selectBar .el-select {
    margin: auto 20px;
}

.search {
    background-color: #202020;
    color: #fff;
}

/* 分页 */

/deep/.el-pagination {
    display: flex;
    justify-content: center;
    margin: 20px auto;
    color: #202020;
}

/deep/.el-pagination button {
    color: #fff;
    background-color: #202020;
}

/deep/ .el-pager li.active {
    color: rgb(255, 150, 50);
}

/deep/ .number {
    color: #fff;
}

/deep/ .number:hover {
    color: rgb(255, 150, 50);
}

/deep/.el-pager li {
    background-color: #202020;
}
</style>
